<?php

namespace App\Logic\Auth\Form;

use App\Core\BaseForm;
use App\Core\Exception\DefaultException;
use App\Core\Exception\ValidationException;
use App\Enums\ValidateEnums;
use App\Logic\Auth\UserService;
use App\Model\Auth\RoleModel;
use App\Model\Merchants\MerchantsModel;
use App\Model\UserModel;
use App\Model\Warehouse\WarehouseModel;
use App\Util\UserIdentityHelper;

class UserSaveForm extends BaseForm{
    
    public $id;
    public $role_id;
    public $username;
    public $psw;
    public $name;
    public $phone;

    public function rules(){
        return [
            'role_id'      => ['required', '角色', '请选择角色'],
            'username'     => ['required|notEmpty|mbLengthMax:100', '登录用户名', '请输入登录用户名'],
            'psw'          => ['required', '密码', '请正确输密码'],
            'name'         => ['required|notEmpty', '姓名', '请输入姓名'],
        ];
    }

    protected $_info;
    
    /**
     * 校验提交数据
     * @return bool
     * @throws DefaultException
     * @throws \EasySwoole\Validate\Exception\Runtime
     */
    public function validate(){
        //生成验证器，方法自动读取rules方法返回的值数据
        $validate = $this->createValidator();

        if(!($check = $validate->validate($this->getAttributes()))){
            throw new DefaultException($validate->getError()->__toString(), 600);
        }
        
        if($this->id && empty($this->getInfo())){
            throw new ValidationException(ValidateEnums::CHECK_REQUIRED,'不存在记录');
        }

        $where = ['username'=>$this->username];
        if($this->id){
            $where['id'] = [$this->id, "<>"];
        }
        if ( UserModel::getCount($where) != 0 ){
            throw new ValidationException(ValidateEnums::CHECK_REQUIRED,'该用户名已经注册');
        }
        
        return true;
    }
    
    /**
     * 保存数据
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Validate\Exception\Runtime
     * @throws \Throwable
     */
    public function saveData(){
        $this->validate();
        
        $data = $this->getAttributeData(['id']);

        if (!empty($this->id) && $this->id == UserModel::SUPER_ADMIN ) {
//            throw new DefaultException('无权修改该用户信息');
        }
        //判断密码
        if ( !empty($this->psw) ){
            list($password,$salt) = (new UserService)->getPassword($this->psw);
            $data['password'] = $password;
            $data['salt'] = $salt;
        }
        
        //审核状态
        $data['type'] = UserModel::TYPE_INSIDE;

        //状态
        $data['state'] = UserModel::ENABLED;

        if($this->id){
            $result = UserModel::updateData($data, ['id' => $this->id]);
    
            UserService::getInstance()->delCache($this->id);
        }else{
            $result = UserModel::insertData($data);
        }
        
        return $this->success(['id' => $this->id ?: $result->lastQueryResult()->getLastInsertId()]);
    }
    
    /**
     * 获取详情
     * @return \App\Core\BaseModel|array|bool|\EasySwoole\ORM\AbstractModel|\EasySwoole\ORM\Db\Cursor|\EasySwoole\ORM\Db\CursorInterface|null
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getInfo(){
        if($this->_info === null){
            $this->_info = UserModel::getOne(['id' => $this->id]);
        }
        return $this->_info;
    }
    
}